﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework.Config;
using log4net.Config;
using MVCActiveRecordIntegration.Models;
using NHibernate.ByteCode.Castle;
using NHibernate.Connection;
using NHibernate.Dialect;
using NHibernate.Driver;
using Environment=NHibernate.Cfg.Environment;

namespace MVCActiveRecordIntegration {
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication {
        public static void RegisterRoutes(RouteCollection routes) {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new {controller = "Person", action = "Index", id = ""} // Parameter defaults
                );
        }

        protected void Application_Start() {
            RegisterRoutes(RouteTable.Routes);
            SetupAR();

            ActiveRecordMediator<Person>.Create(new Person {
                FirstName = "John",
                LastName = "Doe",
                DateOfBirth = new DateTime(1940, 5, 5),
            });
            ActiveRecordMediator<Person>.Create(new Person {
                FirstName = "Jane",
                LastName = "Doe",
                DateOfBirth = new DateTime(1951, 6, 7),
            });
        }

        private void SetupAR() {
            //BasicConfigurator.Configure();
            XmlConfigurator.Configure(new FileInfo(Server.MapPath("/log4net.config")));
            var arConfig = new InPlaceConfigurationSource();
            var properties = new Dictionary<string, string> {
                {Environment.ConnectionDriver, typeof(SQLite20Driver).FullName},
                {Environment.ProxyFactoryFactoryClass, typeof(ProxyFactoryFactory).AssemblyQualifiedName},
                {Environment.Dialect, typeof(SQLiteDialect).FullName},
                {Environment.ConnectionProvider, typeof(DriverConnectionProvider).FullName},
                {Environment.ConnectionString, "Data Source=test.db;Version=3;New=True;"},
            };

            arConfig.Add(typeof (ActiveRecordBase), properties);
            ActiveRecordStarter.ResetInitializationFlag();
            ActiveRecordStarter.Initialize(arConfig, typeof (Person));
            ActiveRecordStarter.CreateSchema();
        }
    }
}